package com.adou.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

/**
 * @description:JDBC事务练习
 * @author:
 * @version: JDBCDemo.java v 0.1
 * @date: 2023.04.01
 */
public class JDBCDemo2 {
    public static void main(String[] args) throws Exception {
        // 1.注册驱动
        Class.forName("com.mysql.jdbc.Driver");

        // 2.获取连接

        String url = "jdbc:mysql://127.0.0.1:3306/db1?useSSL=false";
        String username = "root";
        String password = "root";
        Connection connection = DriverManager.getConnection(url, username, password);

        // 3.sql
        String sql1 = "update account set money = money-500 where id = 1";
        String sql2 = "update account set money = money+500  where id = 2";



        // 4。获取执行sql对象
        Statement statement = connection.createStatement();


        try {
            // 开启事务
            connection.setAutoCommit(false);

            // 5.执行sql
            int result1 = statement.executeUpdate(sql1);
            System.out.println(result1);

//            int i = 3/0;

            int result2 = statement.executeUpdate(sql2);

            // 6.处理结果
            System.out.println(result2);

            // 提交事务
            connection.commit();
        } catch (Exception e) {
            // 回滚事务
            connection.rollback();
        }

        // 7.释放资源
        statement.close();
        connection.close();
    }

}
